package com.skypan.booklistmainactivity;

import android.content.Intent;
import android.os.Bundle;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.LinearSnapHelper;
import androidx.recyclerview.widget.RecyclerView;

import android.util.Log;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.skypan.booklistmainactivity.data.Book;
import com.skypan.booklistmainactivity.data.DataBank;

import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link BookListFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class BookListFragment extends Fragment {

    public static final int RESULT_CODE_EDIT_DATA = 996;
    private List<Book> Books;
    private RecyclerView mRvBook;

    private MyRecyclerViewAdapter adapter;
    private DataBank dataBank;

    ActivityResultLauncher<Intent> launcherAdd = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
        @Override
        public void onActivityResult(ActivityResult result) {
            Intent data = result.getData();
            int resultCode = result.getResultCode();
            if (resultCode == RESULT_CODE_EDIT_DATA){
                if(data == null)return;
                String name = data.getStringExtra("book_name");
                int position = data.getIntExtra("position",0);
                Books.add(position, new Book(name, R.drawable.book_no_name));
                dataBank.saveData();
                adapter.notifyItemInserted(position);
            }
        }
    });

    ActivityResultLauncher<Intent> launcherEdit = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
        @Override
        public void onActivityResult(ActivityResult result) {
            Intent data = result.getData();
            int resultCode = result.getResultCode();
            if(resultCode== RESULT_CODE_EDIT_DATA){
                if(null==data)return;
                String name=data.getStringExtra("book_name");
                int position = data.getIntExtra("position",0);
                Books.get(position).setTitle(name);
                dataBank.saveData();
                adapter.notifyItemChanged(position);
            }

        }
    });


    public BookListFragment() {
        // Required empty public constructor
    }


    public static BookListFragment newInstance() {
        BookListFragment fragment = new BookListFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    private List<Book> getListBooks(){
        return Books;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_book_list, container, false);
        initData();
        Log.d("Books=",Books+"");
        FloatingActionButton fabAdd = view.findViewById(R.id.floating_action_button_add);

        mRvBook = view.findViewById(R.id.recycle_view_items);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this.getContext());
        mRvBook.setLayoutManager(layoutManager);
        adapter = new MyRecyclerViewAdapter(Books);

        mRvBook.setAdapter(adapter);
        mRvBook.setOnFlingListener(new RecyclerView.OnFlingListener() {
            @Override
            public boolean onFling(int velocityX, int velocityY) {

                return false;
            }
        });
        return view;
    }

    public void initData(){
        dataBank = new DataBank(this.getContext());
        Books = dataBank.loadData();
        Books.add(new Book("书",R.drawable.book_1));
    }

    class MyRecyclerViewAdapter extends RecyclerView.Adapter{

        private List<Book> Books;

        public MyRecyclerViewAdapter(List<Book> Books){this.Books = Books;}

        @NonNull
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.layout_book_item,parent,false);

            return new MyViewHolder(view);
        }

        @Override
        public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
            MyViewHolder holder1 = (MyViewHolder)holder;

            holder1.getImageView().setImageResource(Books.get(position).getCoverResourceId());
            holder1.getTextView().setText(Books.get(position).getTitle());
        }

        @Override
        public int getItemCount() {
            return Books.size();
        }


        public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnCreateContextMenuListener, MenuItem.OnMenuItemClickListener{

            private static final int CONTEXT_MENU_ID_ADD = 1;
            private static final int CONTEXT_MENU_ID_EDIT = 2;
            private static final int CONTEXT_MENU_ID_DELETE = 3;

            private final ImageView imageView;
            private final TextView textView;

            public MyViewHolder(@NonNull View itemView) {
                super(itemView);
                this.imageView = itemView.findViewById(R.id.image_view_book_cover);
                this.textView = itemView.findViewById(R.id.text_view_book_title);

                itemView.setOnCreateContextMenuListener(this);
            }

            public ImageView getImageView() { return imageView;}

            public TextView getTextView() {return textView;}

            @Override
            public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
                MenuItem menuItemAdd=menu.add(Menu.NONE,CONTEXT_MENU_ID_ADD,1,R.string.string_menu_add);
                MenuItem menuItemEdit=menu.add(Menu.NONE,CONTEXT_MENU_ID_EDIT,2,R.string.string_menu_edit);
                MenuItem menuItemelete=menu.add(Menu.NONE,CONTEXT_MENU_ID_DELETE,3,R.string.string_menu_delete);

                menuItemAdd.setOnMenuItemClickListener(this);
                menuItemEdit.setOnMenuItemClickListener(this);
                menuItemelete.setOnMenuItemClickListener(this);
            }

            @Override
            public boolean onMenuItemClick(MenuItem item) {
                int position = getAdapterPosition();
                Intent intent = null;
                switch (item.getItemId()){
                    case CONTEXT_MENU_ID_ADD:
                        intent = new Intent(getContext(),EditBookActivity.class);
                        intent.putExtra("position",position);
                        launcherAdd.launch(intent);
                        break;
                    case CONTEXT_MENU_ID_EDIT:
                        intent = new Intent(getContext(), EditBookActivity.class);
                        intent.putExtra("position",position);
                        intent.putExtra("book_name",Books.get(position).getTitle());
                        launcherEdit.launch(intent);
                        break;
                    case CONTEXT_MENU_ID_DELETE:
                        AlertDialog.Builder alertDB = new AlertDialog.Builder(getContext());
                        alertDB.setTitle(getContext().getResources().getString(R.string.hint))
                                .setPositiveButton(getContext().getResources().getString(R.string.string_confirmation), (dialogInterface, i) -> {
                                    Books.remove(position);
                                    dataBank.saveData();
                                    MyRecyclerViewAdapter.this.notifyItemRemoved(position);
                                }).setNegativeButton(getContext().getResources().getString(R.string.string_cancel), (dialogInterface, i) -> {

                        }).setMessage(getContext().getResources().getString(R.string.string_confirm_delete) +Books.get(position).getTitle()+"？").show();
                        break;
                }
                return false;
            }
        }
    }
}